﻿MPT.addAction("microblog_space", function(_elm) {

    //设置4个微博标签
    var nav_jQs = $('.e_nav', _elm);
    var microblog_area_jQ = $(".e_microblog_area", _elm);
    var microblog_page_jQ = $(".e_microblog_page", _elm);
    var friend_group_jQ = $(".e_friend_group", _elm);
    var follow_group_jQ = $(".e_follow_group", _elm);

    var everyone_jQ = $('.e_everyone', _elm);
    var friend_group_jQ = $('.e_friend_group', _elm);
    var follow_group_jQ = $('.e_follow_group', _elm);
    var mine_jQ = $('.e_mine', _elm);
    var myActive_jQ = $('.e_myActive', _elm);
    var atMe_jQ = $('.e_atMe', _elm);

    //微博类型（禁改） 0:大家都在说  1:好友  2:关注  3:我的动态  4:@提到我的
    var blog_type = 0;
    var group_id = 0;
    var user_id = MPT.Config["session"]["userid"];
    var areaList;

    var PAGE_SIZE = 15;

    //========================================微博列表========================================

    var displayMicroblogList = function() {
        microblog_area_jQ.html("");

        switch (blog_type) {
            case 0: displayEveryone(); break;
            default: displayOnePage(1, PAGE_SIZE); break;
        };
    };

    var displayEveryone = function() {
        Backend.microblogIndex1(null, function(_resp) {
            if (Backend.responseValidate(_resp)) {
                var html = [];
                $.each(_resp, function(_i, _b) {
                    _b.blogType = blog_type;
                    html.push(MPT.getTmpl('one_microblog', _b));
                });
                microblog_area_jQ.html(html.join(''));
                microblog_page_jQ.html("<center>没有新鲜事了</center>");
            } else {
                microblog_page_jQ.html("<center>数据加载错误</center>");
            }
        }, function() {
            microblog_page_jQ.html("<center>数据加载错误</center>");
        });
    };

    var displayOnePage = function(_pageNo, _pageSize) {
        var html = [];
        var no_data_hint;
        var cur, total;

        var data = { "targetID": user_id, "pageNo": _pageNo, "pageSize": _pageSize, "groupID": group_id, "selectType": blog_type };

        var addActionScroll = function() {
            var window_height = parseInt($(window).height());
            var dom_height = parseInt($(document).height());
            var dom_top = parseInt($(document).scrollTop());

            if (dom_height - dom_top < window_height + 200) {   //+200作修正
                $(window).unbind('scroll', addActionScroll);
                displayOnePage(cur + 1, PAGE_SIZE);
            }
        };

        var callback = function(_resp) {
            if (Backend.pageBeanValidate(_resp)) {
                var data = _resp.results;
                cur = _resp.pageNo;
                total = _resp.totalPages;

                $.each(data, function(_i, _d) {
                    _d.blogType = blog_type;
                    _d.areaList = areaList;
                    html.push(MPT.getTmpl('one_microblog', _d));
                });
                var onepage_elm = $(html.join(''));

                if (cur != total) {
                    microblog_page_jQ.html("<center>更多动态加载中↓</center>");
                    $(window).bind('scroll', addActionScroll);
                } else {
                    microblog_page_jQ.html("<center>没有新鲜事了</center>");
                    $(window).unbind('scroll', addActionScroll);
                }

                onepage_elm.each(function(_i, _oneblog_elm) { addActionOneBlog(_oneblog_elm) });
                microblog_area_jQ.append(onepage_elm);

            } else {
                microblog_page_jQ.html("<center>" + no_data_hint + "</center>");
            }
        };

        var error = function() {
            microblog_page_jQ.html("<center>数据加载错误</center>");
        };

        switch (blog_type) {
            case 1:
                Backend.findBlogByGID(data, callback, error);
                no_data_hint = "还没有好友动态，请先添加好友";
                break;
            case 2:
                Backend.findBlogByGID(data, callback, error);
                no_data_hint = "还没有微博信息，请先添加关注";
                break;
            case 3:
                Backend.mySpaceTrends(data, callback, error);
                no_data_hint = "您还没有动态";
                break;
            case 4:
                Backend.atMySpaceTrends(data, callback, error);
                no_data_hint = "还没有和您有关的信息";
                break;
        };
    };


    //========================================1条微博========================================

    var addActionOneBlog = function(_blog_elm) {   //注意：_blog_elm为每条微博各自的上下文

        var reHtml = [];

        var blog_body_jQ = $('.e_blog_body', _blog_elm);
        var comment_jQ = $('.e_comment', _blog_elm);
        var transfer_jQ = $('.e_transfer', _blog_elm);
        var comment_jQ = $('.e_comment', _blog_elm);

        var blog_id = $(_blog_elm).attr("id").replace('blog_', '');
        var nick_name = $(_blog_elm).attr("nick");

        var comment_list_jQ, comment_transpond_jQ;

        var content = $(".e_content", _blog_elm).text();
        var trans_content = $(".e_trans_content", _blog_elm).text();


        //---------------------------------------评论及转发 BEGIN---------------------------------------
        var displayCommentList = function() {

            var data = { "blogID": blog_id };

            Backend.loadComment(data, function(_resp) {
                if (Backend.resultValidate(_resp)) {
                    comment_list_jQ = $(MPT.getTmpl('comment_list', _resp['data']));
                    blog_body_jQ.append(comment_list_jQ[0]);

                    if (comment_transpond_jQ) { comment_transpond_jQ.hide(); }

                    addActionComment();
                }
            });
        };

        var addActionComment = function() {

            var comment_add_jQ = $('.e_comment_add', _blog_elm);
            var comment_expand_jQ = $('.e_comment_expand', _blog_elm);
            var comment_after_jQ = $('.e_comment_after', _blog_elm);

            //注意上下文限定在评论框中，避免同转发框混淆
            var input_jQ = $('.e_input', comment_expand_jQ);
            var cancel_jQ = $('.e_cancel', comment_expand_jQ);
            var submit_jQ = $('.e_submit', comment_expand_jQ);

            //评论类型  1为评论  2为回复
            var comment_type = 1;

            (new Publish).create(comment_expand_jQ[0]);

            // 回复框变换
            comment_expand_jQ.hide();
            comment_add_jQ.focus(function() {
                comment_expand_jQ.show();
                comment_add_jQ.hide();
            });

            $(document).not(comment_expand_jQ[0]).mousedown(function() {
                comment_expand_jQ.hide();
                comment_add_jQ.show();
            });

            comment_expand_jQ.mousedown(function(e) {
                e.stopPropagation();
            });

            //回复
            var comment_jQs = $('.e_one_comment', _blog_elm);

            comment_jQs.each(function(_i, _comment_elm) {
                var reply_name = $(_comment_elm).attr("nick");
                var reply_jQ = $('.e_reply', _comment_elm);

                reply_jQ.click(function() {
                    input_jQ.val(" 回复@" + reply_name + " ");
                    comment_add_jQ.hide();
                    comment_expand_jQ.show();
                    input_jQ.focus();
                    comment_type = 2;
                });
            });

            //取消
            cancel_jQ.click(function() {
                comment_add_jQ.show();
                comment_expand_jQ.hide();
            });

            //评论
            submit_jQ.click(function() {

                var content = input_jQ.val();
                if (content == "") {
                    return;
                }
                var data = { 'blogID': blog_id, 'content': content, 'commentType': comment_type, 'publishNickname': nick_name };

                Backend.comment(data, function(_resp) {
                    if (Backend.dataValidate(_resp)) {
                        var new_comment = MPT.getTmpl('one_comment', _resp['data']);
                        comment_after_jQ.after(new_comment);
                        input_jQ.val('');
                    } else {
                        //todo:评论失败
                    }
                });
            });
        };


        //显示转发区域
        var displayTransfer = function() {

            var trans_data = { "blogID": blog_id, "content": content, "nickname": nick_name, "trans_content": trans_content };
            comment_transpond_jQ = $(MPT.getTmpl('transpond_main', trans_data));
            blog_body_jQ.append(comment_transpond_jQ[0]);
            (new Publish).create(comment_transpond_jQ[0]);

            if (comment_list_jQ) { comment_list_jQ.hide(); }
            addActionTransfer();
        };


        //转发区域添加事件
        var addActionTransfer = function() {

            //注意上下文限定在转发框中，避免同评论混淆
            var trans_con_jQ = $('.e_input', comment_transpond_jQ);
            var set_comment_jQ = $('.e_set_comment', comment_transpond_jQ);
            var trans_cancel_jQ = $('.e_cancel', comment_transpond_jQ);
            var trans_submit_jQ = $('.e_submit', comment_transpond_jQ);

            trans_cancel_jQ.click(function() {
                comment_transpond_jQ.hide();
            });

            trans_submit_jQ.click(function() {

                var submit_con = trans_con_jQ.val() + " //@" + nick_name + "：" + content;

                var data = { 'content': submit_con, 'isComment': set_comment_jQ.is(':checked'), 'parentId': blog_id, 'isValidate': true };

                Backend.transBlog(data, function(_resp) {

                    if (Backend.resultValidate(_resp)) {
                        if (_resp.delReason == '-1') {
                            //todo:请勿转发重复内容
                        } else if (_resp.delReason == '-2') {
                            //todo:频率太快 稍后再发
                        } else {
                            trans_con_jQ.val('');
                            $(".e_myActive").click();
                        }
                    } else {
                        //todo:转发失败
                    }
                }, function() {
                    //todo:转发失败
                });
            });
        };
        //-------------------------------------评论及转发 END---------------------------------------

        comment_jQ.one('click', function() {
            displayCommentList();

            // 评论按钮事件
            comment_jQ.click(function() {
                if (comment_transpond_jQ) { comment_transpond_jQ.hide(); }

                if (comment_list_jQ.css('display') == 'none') {
                    comment_list_jQ.show();
                } else {
                    comment_list_jQ.hide();
                }
            });
        });

        transfer_jQ.one('click', function() {
            displayTransfer();

            //转发按钮事件
            transfer_jQ.click(function() {
                if (comment_list_jQ) { comment_list_jQ.hide(); }

                if (comment_transpond_jQ.css('display') == 'none') {
                    comment_transpond_jQ.show();
                }
                else {
                    comment_transpond_jQ.hide();
                }
            });
        });
    };


    //========================================微博导航条========================================

    var displayGroupList = function(_resp) {
        var newGroup = SocialUtil.sortFriendGroup(_resp['data']);
        var html = [];
        $.each(newGroup, function(_i, _g) {
            if (_g != null) { html.push('<a href="javascript:;" groupID="' + _g.groupID + '" title="' + _g.groupName + '">' + _g.groupName + '</a>'); };
        });
        return html.join('');
    }

    var addActionGroupList = function(_group_jQ, _blog_type) {

        _group_jQ.find('a').click(function() {
            blog_type = _blog_type;
            group_id = $(this).attr("groupID");
            displayMicroblogList();
        });

        _group_jQ.find('p').click(function() {
            _group_jQ.find('a').first().click();
        });
    };

    var initEveryone = function() {   //初始化大家        
        $('.e_everyone').click(function() {
            blog_type = 0;
            displayMicroblogList();
        });
    };

    var initFriend = function() {

        //初始化“好友列表”
        Backend.findFriendGroups(null, function(_resp) {
            if (Backend.dataValidate(_resp)) {
                var group_html = displayGroupList(_resp);
                friend_group_jQ.find('.e_subnav').html(group_html);
                addActionGroupList(friend_group_jQ, 1);
            }
        });
    };

    var initFollow = function() {

        //初始化“关注列表”        
        Backend.findFollowGroups(null, function(_resp) {
            if (Backend.dataValidate(_resp)) {
                var group_html = displayGroupList(_resp);
                follow_group_jQ.find('.e_subnav').html(group_html);
                addActionGroupList(follow_group_jQ, 2);
            }
        });
    };

    var initMine = function() {

        myActive_jQ.click(function() {
            blog_type = 3;
            displayMicroblogList();
            //mine_jQ.find('p').text("我的空间动态");
        });

        atMe_jQ.click(function() {
            blog_type = 4;
            displayMicroblogList();
            //mine_jQ.find('p').text("@提到我的");
        });

        mine_jQ.find('p').click(function() {
            myActive_jQ.click();
        });
    };

    //========================================页面初始化========================================

    var initPage = function() {

        //初始化导航条
        initEveryone();
        initFriend();
        initFollow();
        initMine();


        nav_jQs.hover(function() {
            $(this).find('p').addClass('active');
            $(this).find('.e_subnav').show();
        }, function() {
            $(this).find('p').removeClass('active');
            $(this).find('.e_subnav').hide();
        });

        SiteUtil.getServerZone(function(_areaList) {
            areaList = _areaList;
            //初始化微博空间，默认为“大家”
            $('.e_everyone', _elm).click();
        });
    };

    initPage();
});